<template>
  <div class="blog-container">
    <div class="content-wrapper">
      <!-- 动态内容区域 -->
      <div class="content-section">
        <div class="posts-wrapper">
          <el-card v-for="post in posts" :key="post.bid" class="post-item">
            <div class="post-header">
              <img :src="post.avatar" class="avatar" alt="Avatar" />
              <div>
                <span class="username">{{ post.name }}</span>
                <span class="post-time">{{ post.time }}</span>
              </div>
            </div>
            <div class="post-content">
              <p>{{ post.content }}</p>
              <img v-if="post.image" :src="post.image" class="post-image" alt="Post Image" />
            </div>
            <div class="post-actions">
              <el-button type="text" icon="el-icon-thumb" @click="likePost(post.bid)">
                {{ post.likesNumber }} 点赞
              </el-button>
              <el-button type="text" icon="el-icon-message" @click="toggleComments(post.bid)">
                {{ post.commentsNumber }} 评论
              </el-button>
              <el-button type="text" icon="el-icon-share" @click="sharePostToWeibo(post)">分享</el-button>
            </div>
          </el-card>
        </div>
      </div>

      <!-- 排行榜区域 -->
      <div class="ranking-section">
        <h3 class="ranking-title">热门帖子</h3>
        <div class="ranking-list">
          <el-card v-for="post in rankedPosts" :key="post.bid" class="ranking-item">
            <div class="ranking-header">
              <img :src="post.avatar" class="avatar" alt="Avatar" />
              <div>
                <span class="username">{{ post.name }}</span>
                <span class="post-time">{{ post.time }}</span>
              </div>
            </div>
            <div class="post-content">
              <p>{{ post.content }}</p>
              <img v-if="post.image" :src="post.image" class="post-image" alt="Post Image" />
            </div>
            <div class="post-actions">
              <el-button type="text" icon="el-icon-thumb">
                {{ post.likesNumber }} 点赞
              </el-button>
            </div>
          </el-card>
        </div>
      </div>
    </div>

    <!-- 右下角写博客按钮 -->
    <el-button
      class="write-blog-btn"
      type="primary"
      icon="el-icon-edit"
      circle
      @click="openBlogDialog"
    ></el-button>

    <!-- 写博客对话框 -->
    <el-dialog title="写博客" :visible.sync="dialogVisible">
      <el-form :model="newPost">
        <el-form-item label="内容">
          <el-input
            type="textarea"
            rows="5"
            v-model="newPost.content"
            placeholder="分享你的旅行故事..."
          ></el-input>
        </el-form-item>
        <el-form-item label="图片">
          <el-upload
            class="upload-demo"
            action=""
            list-type="picture-card"
            :file-list="newPost.imageList"
            :auto-upload="false"
            :on-change="handleImageChange"
            :on-remove="handleImageRemove"
          >
            <i slot="default" class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="pushBlog">发布</el-button>
      </div>
    </el-dialog>

    <!-- 评论 -->
    <div v-if="isModelVisible" class="modal-overlay">
      <div class="modal-content">
        <div class="modal-header">
          <span class="modal-title">评论信息</span>
          <span class="close-button" @click="handleClose">X</span>
        </div>
        <div class="modal-body">
          <div v-for="comment in comments" :key="comment.cid" class="comment-card">
            <div class="comment-uid"> {{ comment.commentname }}</div>
            <div class="comment-content">{{ comment.comment }}</div>
          </div>
        </div>
        <div class="modal-footer">
          <textarea v-model="commentContent" placeholder="请输入评论" class="comment-input"></textarea>
          <button :disabled="!commentContent.trim()" class="submit-button" @click="handleSubmit">发表</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { selectAllFmerBlogs, likePost, selectAllComments, pushComment, pushBlog } from '@/api/blog';

export default {
  data() {
    return {
      // 排行榜
      rankedPosts: [], // 排行榜数据

      // 评论
      isModelVisible: false,
      commentContent: '',
      comentBid: '',
      comments: [
        {
          "cid": 1,
          "uid": "1471314385",
          "bid": 1,
          "time": "2024-12-11T21:07:30.000+00:00",
          "comment": "之前我就想去江西来着，没想到这么漂亮，更想去了！",
          "commentname": "石桥"
        }
      ],

      // 发布新的blog
      dialogVisible: false,
      newPost: {
        content: "",
        imageList: [],
      },
      posts: [
        {
          "bid": 1,
          "uid": "2771651667",
          "time": "2024-12-06T01:54:48.000+00:00",
          "image": "https://loremflickr.com/400/400?lock=8424403570849280",
          "content": "今日出游",
          "likesNumber": 100,
          "commentsNumber": 100,
          "name": "会飞的猪",
          "avatar": "https://loremflickr.com/400/400?lock=8424403570849280",
          "like_status": 1
        },
        {
          "bid": 2,
          "uid": "1471314386",
          "time": "2024-12-16T14:36:22.000+00:00",
          "image": "https://loremflickr.com/400/400?lock=8424403570849280",
          "content": "明日日日出游",
          "likesNumber": 200,
          "commentsNumber": 7,
          "name": "会飞的俞",
          "avatar": "https://loremflickr.com/400/400?lock=8424403570849280",
          "like_status": 1
        }
      ],
    };
  },

  mounted() {
    selectAllFmerBlogs().then(res => {
      this.posts = res.data.data;
      this.rankPosts(); // 排序帖子
    });
  },

  methods: {
    // 排序帖子，按点赞数排序
    rankPosts() {
      this.rankedPosts = this.posts.slice().sort((a, b) => b.likesNumber - a.likesNumber).slice(0, 5);
    },

    // 分享到微博
    sharePostToWeibo(post) {
      const postUrl = window.location.href;  // 当前页面的 URL
      const weiboShareUrl = `https://service.weibo.com/share/share.php?url=${encodeURIComponent(postUrl)}&title=${encodeURIComponent(post.name)}&content=${encodeURIComponent(post.content)}`;
      // 打开微博分享页面
      window.open(weiboShareUrl, '_blank');
    },

    // 评论
    handleClose() {
      this.isModelVisible = false;
    },

    handleSubmit() {
      if (!this.commentContent.trim()) return;
      
      const par = {
        bid: this.comentBid,
        comment: this.commentContent
      };

      pushComment(par)
        .then(() => {
          const newComment = {
            cid: new Date().getTime(),
            commentname: '当前用户',  // 假设为当前用户的名称
            comment: this.commentContent
          };
          this.comments.push(newComment);
          this.commentContent = '';
        })
        .catch(() => {
          this.$message.error("评论失败，请重试！");
        });
    },

    // Blog
    openBlogDialog() {
      this.dialogVisible = true;
    },

    pushBlog() {
      const formData = new FormData();
      if (this.newPost.imageList && this.newPost.imageList.length > 0) {
        formData.append('image', this.newPost.imageList[0].raw);
      }
      formData.append('blog', JSON.stringify({
        content: this.newPost.content
      }));

      pushBlog(formData)
        .then((res) => {
          if (res.data.code === 1) {
            this.dialogVisible = false;
            this.newPost = { content: "", imageList: [] };
            this.$message.success("发布成功！");
            selectAllFmerBlogs().then(res => {
              this.posts = res.data.data;
              this.rankPosts();
            })
          } else {
            this.$message.error(res.data.message || "发布失败！");
          }
        })
        .catch(() => {
          this.$message.error("上传失败，请重试！");
        });
    },

    likePost(bid) {
      likePost(bid)
        .then(() => {
          selectAllFmerBlogs().then(res => {
            this.posts = res.data.data;
            this.rankPosts();
          })
        });
    },

    toggleComments(bid) {
      selectAllComments(bid)
        .then(res => {
          this.comments = res.data.data;
        })
      this.comentBid = bid;
      this.isModelVisible = true;
    },

    handleImageChange(file, fileList) {
      this.newPost.imageList = fileList;
    },

    handleImageRemove(file, fileList) {
      this.newPost.imageList = fileList;
    }
  }
};
</script>

<style scoped>
/* 排行榜区域样式 */
.ranking-section {
  width: 100%;
  max-width: 350px; /* 限制排行榜的最大宽度 */
  margin: 20px 0;
  background-color: #fff;
  padding: 15px;
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  float: right; /* 使排行榜浮动到右边 */
}

.ranking-title {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin-bottom: 15px;
}

.ranking-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.ranking-item {
  padding: 10px;
  background-color: #f9f9f9;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.ranking-header {
  display: flex;
  align-items: center;
}

.ranking-header .avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 10px;
}

.username {
  font-weight: bold;
}

.post-time {
  font-size: 12px;
  color: #888;
}

.post-actions {
  margin-top: 10px;
  font-size: 14px;
}

.el-button {
  color: #007bff;
}

/* 动态内容区域样式 */
.content-section {
  width: 100%;
  max-width: 750px; /* 限制帖子部分的最大宽度 */
  margin: 20px;
  float: left; /* 使帖子浮动到左边 */
  clear: both; /* 清除浮动 */
}

.posts-wrapper {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.post-item {
  padding: 10px;
  background-color: #f9f9f9;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.post-header {
  display: flex;
  align-items: center;
}

.post-header .avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 10px;
}

.username {
  font-weight: bold;
}

.post-time {
  font-size: 12px;
  color: #888;
}

.post-actions {
  margin-top: 10px;
  font-size: 14px;
}

.el-button {
  color: #007bff;
}

/* 图片样式 */
.post-image, .ranking-item img {
  max-width: 90%; /* 限制图片的最大宽度 */
  max-height: 500px;
  border-radius: 8px; /* 图片的圆角 */
}

/* 写博客按钮 */
.write-blog-btn {
  position: fixed;
  bottom: 30px;
  right: 30px;
  background-color: #ff6f61;
  border-radius: 50%;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.2);
}

/* 写博客对话框样式 */
.el-dialog {
  max-width: 600px; /* 限制对话框的最大宽度 */
}

.el-form-item label {
  font-size: 14px;
  font-weight: bold;
}

.el-input {
  font-size: 14px;
}

.el-upload {
  border: 2px dashed #ccc;
  padding: 20px;
}

.el-upload i {
  font-size: 24px;
  color: #ccc;
}

.el-dialog .dialog-footer {
  display: flex;
  justify-content: space-between;
}

/* 评论弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}

.modal-content {
  background: white;
  padding: 20px;
  border-radius: 10px;
  max-width: 500px;
  width: 100%;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.comment-input {
  width: 100%;
  padding: 10px;
  margin-top: 10px;
  border: 1px solid #ccc;
  border-radius: 8px;
}

.submit-button {
  margin-top: 10px;
  padding: 10px;
  background-color: #ff6f61;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
}

.submit-button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

/* 头部样式 */
.header {
  background-color: #f8f9fa;
  padding: 20px;
  text-align: center;
  border-bottom: 2px solid #ddd;
}

.header h1 {
  font-size: 32px;
  font-weight: bold;
  color: #333;
}

/* 导航栏样式 */
.navbar {
  display: flex;
  justify-content: space-around;
  background-color: #007bff;
  padding: 10px;
}

.navbar a {
  color: white;
  text-decoration: none;
  font-size: 16px;
}

.navbar a:hover {
  text-decoration: underline;
}

/* 背景色 */
body {
  background-color: #f4f7f6;
  font-family: 'Arial', sans-serif;
}

/* 页脚样式 */
.footer {
  background-color: #222;
  color: white;
  padding: 20px;
  text-align: center;
}

.footer a {
  color: #007bff;
  text-decoration: none;
}

.footer a:hover {
  text-decoration: underline;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .ranking-section {
    max-width: 100%;
    margin-top: 20px;
  }

  .content-section {
    max-width: 100%;
    margin: 20px 0;
  }

  .navbar {
    flex-direction: column;
    align-items: center;
  }
}

</style>
